package com.hskn.hss.module.procurementPlan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.instorageCfg.entity.TlInStorageCfg;
import com.hskn.hss.module.instorageCfg.mapper.TlInStorageCfgMapper;
import com.hskn.hss.module.planDetail.entity.TlPlanDetail;
import com.hskn.hss.module.planDetail.service.ITlPlanDetailService;
import com.hskn.hss.module.procurementPlan.entity.TlProcurementPlan;
import com.hskn.hss.module.procurementPlan.mapper.TlProcurementPlanMapper;
import com.hskn.hss.module.procurementPlan.service.ITlProcurementPlanService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.AuthoritySqlUtils;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-07
 */
@Service
public class TlProcurementPlanServiceImpl extends ServiceImpl<TlProcurementPlanMapper, TlProcurementPlan> implements ITlProcurementPlanService {

    @Resource
    TlProcurementPlanMapper tlProcurementPlanMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlPlanDetailService tlPlanDetailService;
    @Resource
    TlInStorageCfgMapper tlInStorageCfgMapper;
    @Autowired
    AuthoritySqlUtils authoritySqlUtils;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult insert(JSONObject params) {

        String uid = LoginUtils.getUser().getUid();
        TlProcurementPlan tlProcurementPlan = params.getObject("data", TlProcurementPlan.class);

        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();

        tlProcurementPlan.setCreateby(uid);
        tlProcurementPlan.setCreatetime(new Date());
        tlProcurementPlan.setId(StringUtils.uuid());
        tlProcurementPlan.setDeptid(deptid);
        tlProcurementPlan.setApplicationtotlnum(tlProcurementPlan.getDateils().size());
        int applicationnum = 0;
        //添加对应的 明细
        for (TlPlanDetail tlPlanDetail : tlProcurementPlan.getDateils()) {
            tlPlanDetail.setId(StringUtils.uuid());
            tlPlanDetail.setPlanid(tlProcurementPlan.getId());
            applicationnum += tlPlanDetail.getItemnum();
            JSONObject dateilParam = new JSONObject().fluentPut("data", tlPlanDetail);
            try {
                tlPlanDetailService.insert(dateilParam);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("报错ERROR", e);
                return AjaxResult.fail("明细表添加失败，请稍后再试");
            }
        }
        tlProcurementPlan.setApplicationnum(applicationnum);
        int i = tlProcurementPlanMapper.insert(tlProcurementPlan);
        boolean flag = i > 0 ? true : false;

        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult update(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlProcurementPlan tlProcurementPlan = params.getObject("data", TlProcurementPlan.class);

        tlProcurementPlan.setUpdateby(uid);
        tlProcurementPlan.setUpdatetime(new Date());
        tlProcurementPlan.setApplicationtotlnum(tlProcurementPlan.getDateils().size());
        int applicationnum = 0;

        //添加对应的 操作权限
        tlPlanDetailService.deleteByMap(tlProcurementPlan.getId());
        //添加对应的 明细
        for (TlPlanDetail tlPlanDetail : tlProcurementPlan.getDateils()) {
            tlPlanDetail.setId(StringUtils.uuid());
            tlPlanDetail.setPlanid(tlProcurementPlan.getId());
            applicationnum += tlPlanDetail.getItemnum();
            JSONObject dateilParam = new JSONObject().fluentPut("data", tlPlanDetail);
            try {
                tlPlanDetailService.insert(dateilParam);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("报错ERROR", e);
                return AjaxResult.fail("明细表添加失败，请稍后再试");
            }
        }
        tlProcurementPlan.setApplicationnum(applicationnum);
        int i = tlProcurementPlanMapper.updateById(tlProcurementPlan);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public AjaxResult deleteByid(JSONObject params) throws HssException {
        String id = params.getString("id");
        int i = tlProcurementPlanMapper.deleteById(id);
        tlPlanDetailService.deleteByMap(id);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    public TlProcurementPlan getDetailById(JSONObject params) throws HssException {
        String id = params.getString("id");
        TlProcurementPlan TlProcurementPlan = tlProcurementPlanMapper.selectById(id);
        List<TlPlanDetail> TlPlanDetailList = tlPlanDetailService.getitemListByParentId(id);
        if (!TlPlanDetailList.isEmpty()) {
            TlProcurementPlan.setDateils(TlPlanDetailList);
        }
        return TlProcurementPlan;
    }

    @Override
    public JSONObject getList(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
//        AuthoritySqlUtils authoritySqlUtils = new AuthoritySqlUtils();
        String antusql = authoritySqlUtils.GetAuthoritySqlByUid(uid, "createby", "deptid");

        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();
        Map map = new HashMap();
        map.put("planname", params.getString("planname"));
        map.put("storagecenterid", params.getString("storagecenterid"));
        map.put("applicationperson", params.getString("applicationperson"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
        map.put("auditperson", uid);
        map.put("antusql", antusql);
        map.put("status", params.getString("status"));


        Page<TlProcurementPlan> planPage = new Page<>(page, size, true);
        IPage<TlProcurementPlan> iPage = tlProcurementPlanMapper.listProcurementPlan(planPage, map);

        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("planlist", iPage.getRecords());
        return json;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult audit(JSONObject params) {

        String uid = LoginUtils.getUser().getUid();
        String id = params.getString("id");
        String auditReason = params.getString("auditreason");
        String status = params.getString("status");
        TlProcurementPlan tlProcurementPlan = tlProcurementPlanMapper.selectById(id);
        tlProcurementPlan.setAuditperson(uid);
        tlProcurementPlan.setAudittime(new Date());
        tlProcurementPlan.setAuditremark(auditReason);
        tlProcurementPlan.setStatus(status);
        if (status.equals("1")) {
            TlInStorageCfg tlInStorageCfg = new TlInStorageCfg();
            tlInStorageCfg.setId(StringUtils.uuid());
            tlInStorageCfg.setStatus("0");
            tlInStorageCfg.setPlanid(tlProcurementPlan.getId());
            tlInStorageCfg.setSerialnumber(StringUtils.Serialnumber());
            tlInStorageCfg.setStoragecenterid(tlProcurementPlan.getStoragecenterid());
            tlInStorageCfg.setItemtotalnum(tlProcurementPlan.getApplicationnum());
            tlInStorageCfg.setItemtotalprice(tlProcurementPlan.getPlanningbudget());
            tlInStorageCfgMapper.insert(tlInStorageCfg);
        } else if (status.equals("3")) {
            QueryWrapper<TlInStorageCfg> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TlInStorageCfg::getPlanid, id);
            String storageid = tlInStorageCfgMapper.selectOne(queryWrapper).getId();
            if (!"".equals(storageid) || storageid != null) {
                tlInStorageCfgMapper.deleteById(storageid);
            }
        }
        try {
            tlProcurementPlanMapper.updateById(tlProcurementPlan);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败,请稍后再试");
        }
    }
}
